package com.pi.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@RestController
@RequestMapping("/common")
public class CommonController {

    static String basePath="D:\\Download\\BingImages\\";

    @Autowired
    private WebClient webClient;

    @GetMapping("/1")
    public String  hello(){
        return "hello";
    }


    /**
     * 生成图片保存路径
     * @param imageUrl 图片 URL
     * @return 文件路径
     */
    private Mono<String> downloadImage(String imageUrl) {
        int index = imageUrl.indexOf("/");
        String imageDir = imageUrl.substring(index + 2, index + 8);
        String imageName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
        String savePath = basePath + "temp\\" + imageDir + "\\" + imageName;
        return Files.exists(Paths.get(savePath))
                ? Mono.empty() // 如果文件已存在，跳过下载
                : downloadImage(imageUrl, savePath);
    }


    /**
     * 下载单个图片
     *
     * @param imageUrl 图片 URL
     * @return Mono<String> 下载结果
     */
    public Mono<String> downloadImage(String imageUrl,String savePath) {
        return webClient.get()
                .uri(imageUrl)
                .retrieve()
                .bodyToMono(byte[].class)
                .flatMap(bytes -> {
                    try {
                        // 确保目录存在
                        Files.createDirectories(Paths.get(savePath).getParent());
                        // 保存图片到本地
                        try (FileOutputStream fos = new FileOutputStream(savePath)) {
                            fos.write(bytes);
                        }
                        return Mono.just("图片下载成功: " + savePath);
                    } catch (IOException e) {
                        return Mono.error(e);
                    }
                })
                .onErrorResume(e -> {
                    // 记录错误日志
                    System.err.println("图片下载失败: " + imageUrl + "，错误信息: " + e.getMessage());
                    return Mono.empty(); // 忽略错误，继续执行
                })
                .retry(3) // 重试 3 次
                .subscribeOn(Schedulers.boundedElastic()); // 限制并发
    }
}
